package com.cyclecoder.thread;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.FutureTask;

/**
 * @author by zhanglei
 * @Date 2021/8/9
 */
public class ThreadRunableDemo implements Runnable {
    int ticket = 10;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                if (ticket < 1) {
                    break;
                }
                System.out.println(ticket);
                ticket--;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
        //CountDownLatch用法
//        CountDownLatch cd = new CountDownLatch(4);
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//
//                try {
//                    System.out.println(Thread.currentThread().getName()+"开始前");
//                    int a = new Random().nextInt(5);
//                    Thread.sleep(a*1000);
//                    System.out.println(Thread.currentThread().getName()+">>>"+a);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }finally {
//                    cd.countDown();
//                }
//            }
//        };
//
//        new Thread(runnable).start();
//        new Thread(runnable).start();
//        new Thread(runnable).start();
//        new Thread(runnable).start();
//        cd.await();
//        System.out.println("finished");

        CyclicBarrier cyclicBarrier = new CyclicBarrier(4);
        Callable callable = new Callable() {
            @Override
            public Object call() throws Exception {
                int a = new Random().nextInt(10);
                Thread.sleep(a * 1000);
                System.out.println(Thread.currentThread().getName() + "开始前");

                cyclicBarrier.await();

                Thread.sleep(a * 1000);
                System.out.println(Thread.currentThread().getName() + ">>>" + a);
                cyclicBarrier.await();
                System.out.println("ddddddddddddd");

                return null;
            }
        };
        new Thread(new FutureTask<>(callable)).start();
        new Thread(new FutureTask<>(callable)).start();
        new Thread(new FutureTask<>(callable)).start();
        new Thread(new FutureTask<>(callable)).start();

        System.out.println("finished");
    }
}
